package com.soriya.nestlive.screen.sign

import android.content.Context
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Checkbox
import androidx.compose.material.CheckboxDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.soriya.nestlive.component.CustomEditText
import com.soriya.nestlive.component.MediumText
import com.soriya.nestlive.component.ScreenColumnContent
import com.soriya.nestlive.component.SmallTitle
import com.soriya.nestlive.constant.CommonConstant
import com.soriya.nestlive.constant.UIValue
import com.soriya.nestlive.util.ToastUtil
import com.soriya.nestlive.viewmodel.UserModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch

@Composable
fun SignInScreen(
    toSignUp: () -> Unit,
    signIn: () -> Unit
) {
    ScreenColumnContent(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.SpaceBetween,
        modifier = Modifier
            .fillMaxSize()
    ) {

        SignTop()

        SignInForm(modifier = Modifier, signIn = signIn)

        Spacer(modifier = Modifier)

        SignBottom {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.Center
            ) {
                Text(
                    text = "Already have on account? ",
                    textAlign = TextAlign.Center,
                    color = MaterialTheme.colors.surface.copy(0.5F)
                )
                Text(
                    text = "Sign up",
                    textAlign = TextAlign.Center,
                    color = MaterialTheme.colors.primary,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.clickable {
                        toSignUp()
                    }
                )
            }
        }
    }
}

@Composable
fun SignInForm(
    modifier: Modifier = Modifier,
    signIn: () -> Unit
) {
    val context = LocalContext.current

    val model: UserModel = hiltViewModel()

    var hasRememberMe by remember {
        mutableStateOf(false)
    }

    var accountValue by remember { mutableStateOf("") }

    var passwordValue by remember { mutableStateOf("") }

    Column(
        modifier = modifier
    ) {

        val editTextBackground: Color = MaterialTheme.colors.surface.copy(alpha = 0.04F)

        CustomEditText(
            value = accountValue,
            onValueChange = {
                accountValue = it
            },
            placeholder = "Account",
            leftIcon = Icons.Default.AccountCircle,
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = editTextBackground
            ),
            shape = RoundedCornerShape(UIValue.LARGE_RADIUS),
            modifier = Modifier
                .fillMaxWidth()
        )

        Spacer(modifier = Modifier.height(20.dp))

        CustomEditText(
            value = passwordValue,
            onValueChange = {
                passwordValue = it
            },
            placeholder = "Password",
            leftIcon = Icons.Default.AccountCircle,
            visualTransformation = PasswordVisualTransformation(),
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = editTextBackground
            ),
            shape = RoundedCornerShape(UIValue.LARGE_RADIUS),
            modifier = Modifier
                .fillMaxWidth()
        )

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Center
        ) {
            Checkbox(
                checked = hasRememberMe,
                onCheckedChange = {
                    hasRememberMe = it
                },
                colors = CheckboxDefaults.colors(
                    checkedColor = MaterialTheme.colors.primary,
                    uncheckedColor = MaterialTheme.colors.primary
                )
            )
            SmallTitle(text = "Remember Me", color = MaterialTheme.colors.primary)
        }

        val coroutineScope = rememberCoroutineScope()

        Button(
            onClick = {
                coroutineScope.launch {
                    model.login(accountValue, passwordValue)
                        .catch {
                            it.printStackTrace()
                            Log.i("SoRiya", "catch: ${it.message}")
                            ToastUtil.show(context, it.message!!)
                        }.collect {
                            // 登录成功
                            val sharedPreferences =
                                context.getSharedPreferences(CommonConstant.USER_INFO_KEY, Context.MODE_PRIVATE)
                            val edit = sharedPreferences.edit()
                            edit.putString("token", it)
                            edit.apply()
                            signIn()
                        }
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp),
            shape = RoundedCornerShape(50)
        ) {
            MediumText(text = "Sign in")
        }

        Spacer(modifier = Modifier.height(20.dp))

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.Center
        ) {
            SmallTitle(text = "Forgot Password?", color = MaterialTheme.colors.primary)
        }
    }
}